using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System;
using SiteManager;
using System.Text;
using System.IO;

/// <summary>
/// USER CONTROL TO ADD/EDIT DENTIST DATA
/// </summary>
/// <remarks>
/// AUTHOR  : KAJAL MANDAL
/// DATE    : 5 MAY 2007
/// </remarks>
public partial class includes_ctrlDentistReg : System.Web.UI.UserControl
{
    string errorMessage = String.Empty;
    string filename = String.Empty;
    public string strRedirect = string.Empty;
    private int DentistId=0;
    
    public int DentistIdentificationNumber        //WRITE ONLY
    { set { DentistId = value; } }
    

    Manager mgr = new Manager(true,"ConnectionString");
    protected void Page_Load(object sender, EventArgs e)
    {

        if (ViewState["Pwd"] != null)
        {
            txtPwd1.Attributes.Add("value", ViewState["Pwd"].ToString());
            txtpwd2.Attributes.Add("value", ViewState["Pwd"].ToString());
        }
        if (Request.ServerVariables["script_name"].ToString().ToUpper().IndexOf("ADMIN") > 0)
        { lblHeading.Visible = true; }
        else
        { lblHeading.Visible = false; }

        btnAddInsurance.Attributes.Add("onclick", "window.open('../admin/Insurance_Add.aspx',null,'height=200,width=450,status=yes,toolbar=no,menubar=no,location=no');return false;");
        //if (ViewState["Action"] == null)
        //    ViewState["Action"] = Session["pageFromOrAction"];


        if (!IsPostBack)
        {
            DentistId = 0;
            if (Request.QueryString["id"] != null)
            {
                try
                {
                    DentistId = Convert.ToInt32(Request.QueryString["id"]);
                    lblHeading.Text = "Update Dentist"; //FillControls(DentistId);
                    FillControls(DentistId);
                }
                catch { }
            }
            else
            {
                lblHeading.Text = "Add Dentist";
                FillControls(0);
            }
        }
        else
        {
            ////ViewState["Count"] = 1;
            //Session["InsId"] = "";
            //if (DentistId > 0)
            //{
            //    FillControls(DentistId);
            //}   
            if (Request.QueryString["id"] != null)
            { DentistId = Convert.ToInt32(Request.QueryString["id"]); }
        }
    }

    /// <summary>
    /// THIS FILLS ALL DROP DOWN LIST AND USER INFORMATION 
    /// </summary>
    /// <param name="id"></param>
    /// <remarks>
    /// FILED CODE
    /// </remarks>
    public void FillControls(int id)
    {

        int tYear = DateTime.Today.Year;
        for (int i = 1950; i <= tYear; i++)
        {
            ddlGradYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }
        ///...By Ian
        //clsGeneral.BindState(ddlState);
        mgr.BindList("select [countryname],countrycode from tbl_country where(countrycode='US')OR (countrycode='CA') order by [countryname]", "countryname", "countrycode", ddlCountry, "select");
        mgr.BindList("select id,name from tbl_MajorActivity order by name", "name", "id", ddlMajorActivity, "select");
        mgr.BindList("select stateid,name from tbl_states order by name", "Name", "StateId", ddlState, "select");
        mgr.BindListBox("select id,name from tbl_InsuranceCompanies order by name", "name", "Id", lstInsurance, "select");
        lstInsurance.Items.Add(new ListItem("--NONE--", "-1"));

        ddlAdvTraining.Items.Clear();
        ddlAdvTraining.Items.Add(new ListItem("Yes", "Y"));
        ddlAdvTraining.Items.Add(new ListItem("No", "N"));

        ddlnewPat.Items.Clear();
        ddlnewPat.Items.Add(new ListItem("Yes", "1"));
        ddlnewPat.Items.Add(new ListItem("No", "0"));

        //Edit a doctor's info
        if (id > 0)
        {
            clsDentist dent = new clsDentist(DentistId);
            //DataSet ds = mgr.ExecuteQuery("select * from tbl_doctors where  isdelete=0 and id='" + id + "';SELECT InsuranceID FROM tbl_Doctor_Insurance WHERE DoctorID='" + id + "'", "tblDoctor");            
            
            //if (ds.Tables[0].Rows.Count > 0)
            if (!dent.HasError)
            {
                txtFname.Text = dent.FNAME;
                txtMName.Text = dent.MNAME;
                txtLName.Text = dent.LNAME;
                txtEmail.Text = dent.EMAIL;
                ViewState["email"] = txtEmail.Text;
                txtEmail.Attributes.Add("value", dent.EMAIL);
                txtPwd1.Attributes.Add("value", dent.PASSWORD);
                txtpwd2.Attributes.Add("value", dent.PASSWORD);                
                txtTitle.Text = dent.TITLE;
                bool ss = dent.GENDER.Equals("M") ? rbGender.Checked = true : rbGender2.Checked = true;
                txtLanguages.Text = dent.LANGUAGES;
                txtPhone.Text = dent.PHONE;
                txtFax.Text = dent.FAX;
                txtAddress1.Text = dent.ADDRESS1;
                txtAddress2.Text = dent.ADDRESS2;
                txtCity.Text = dent.CITY;
                txtCounty.Text = dent.COUNTY;
                txtZipCode.Text = dent.ZIPCODE;
               
                    txtPhoto.Text = dent.PHOTO;
              

                txtGroupPractise.Text = dent.GROUPPRACTICE;
                
                #region New Code Added By Prashant Tomar August 10, 2007
                
                rbtAbms1.Checked = dent.ABMS_CERTIFICATIONID;
                rbtAbms2.Checked = !dent.ABMS_CERTIFICATIONID;                
                // Code Commented By Prashant Tomar Augest 10, 2007
                //bool test = dent.ABMS_CERTIFICATIONID ? rbtAbms1.Checked = true : rbtAbms2.Checked = true;
                rbAEGDYes.Checked = dent.AEGD;
                rbAEGDNo.Checked = !dent.AEGD;
                
                rbMarksYes.Checked = dent.MARKSOFDISTICTION;
                rbMarksNo.Checked = !dent.MARKSOFDISTICTION;
                
                rbSpYes.Checked = dent.SPECIALITYBOARD;
                rbSpNo.Checked = !dent.SPECIALITYBOARD;
                #endregion

                txtAwards.Text = dent.AWARDS;
                
                if (dent.ADVANCEDTRAINING.Equals("N"))
                { ddlAdvTraining.Items.FindByValue("N").Selected = true; }
                else { ddlAdvTraining.Items.FindByValue("Y").Selected = true; }

                if (dent.ACCEPTNEW)
                { ddlnewPat.Items.FindByValue("1").Selected = true; }
                else { ddlnewPat.Items.FindByValue("0").Selected = true; }
                
                string StateCode = dent.STATE;
                string CountryId = dent.COUNTRYID;
                string SpecialityID = dent.SPECIALITYID.ToString();
                //string PrimarySpecialityID = dent.PRIMARYSPECIALITYID.ToString();
                string SecondarySpecialityID = dent.SECONDARYSPECIALITYID.ToString();
                string MajorActivityId = dent.MAJORACTIVITYID.ToString();
                hdnSpecialty.Value = SpecialityID;                
                //hdnPSpecialty.Value = PrimarySpecialityID;
                hdnSSpecialty.Value = SecondarySpecialityID;

                
                SqlDataReader rdr = mgr.ExecuteQuery("SELECT InsuranceID FROM tbl_Dentist_Insurance WHERE DentistID='" + dent.ID + "'");

                while (rdr.Read())
                {
                    if (lstInsurance.Items.FindByValue(rdr[0].ToString()) != null)
                        lstInsurance.Items.FindByValue(rdr[0].ToString()).Selected = true;
                }
                rdr.Close();

                try
                {
                    ddlCountry.SelectedValue = CountryId;
                    ddlState.SelectedValue = StateCode;
                    ddlMajorActivity.SelectedValue = MajorActivityId;
                    ddlGradYear.SelectedValue = dent.GRADUATIONYEAR.ToString();
                    // ds.Tables[0].Rows[0]["GraduationYear"].ToString().Trim();
                }
                catch (Exception ex)
                {
                    lblErrorMessage.Text = ex.ToString();
                }

                hdnHospital.Value = lblHospital.Text = dent.HOSPITALNAME.Replace(";", "<BR>");
                hdnMedSch.Value = dent.MEDICALSCHOOL.ToString();
            }
            else
            {
                Response.Write(dent.ErrorDescription);
                return;
            }
        }
        return;
    }
    
    protected void btnAddInsurance_Click(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// filed code. not in use.
    /// </summary>
    /// <param name="clientId"></param>
    /// <param name="serverId"></param>
    /// <returns></returns>
    private string GetHTMLNameById(string clientId, string serverId)
    {
        int pos = serverId.IndexOf('_');
        string HTMLName = "";
        if (pos >= 0)
        {
            pos = clientId.IndexOf(serverId);
            HTMLName = clientId.Remove(pos, serverId.Length);
            HTMLName = HTMLName.Replace('_', '$');
            HTMLName += serverId;
        }
        else
            HTMLName = clientId.Replace('_', '$');        
        return HTMLName;
    }

    protected void wiz_DentistReg_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
      //string photo=  fupl_photo.FileName;
       
     // Session["photo"] = photo;
        Validation validateForm = new Validation();
        if (fupl_photo.HasFile)
        {
            string ImgPath1 = "../images/Dnt_images/";
            string filename1 = Path.GetFileName(fupl_photo.PostedFile.FileName);
            string baseFile = Path.GetFileNameWithoutExtension(fupl_photo.PostedFile.FileName);
            string extension = Path.GetExtension(fupl_photo.PostedFile.FileName);
            int fileMatchCount = 1;
            // Check if a file with the given name exists in the Images1 subfolder of the root folder of your site
            while (File.Exists(Server.MapPath(Path.Combine(ImgPath1, filename1))))
            {
                //filename1 = string.Format("{0}({1:D3}){2}", baseFile, fileMatchCount, extension);
                filename1 = string.Format("{0}({1:D2}){2}", baseFile, fileMatchCount, extension);
                fileMatchCount++;
            }
            fupl_photo.SaveAs(Server.MapPath(Path.Combine(ImgPath1, filename1)));
            Session["photo"] = filename1;
        }
      //if (fupl_photo.HasFile)
      //{
      //    string Existingphoto = "";
      //    errorMessage = mgr.UpLoadFile(fupl_photo, Server.MapPath("../images/Dnt_images/"), ".jpg|.bmp|.gif|.jpeg", 512000);
      //    if (errorMessage.Length > 0)
      //    {

      //        //lblMessage.Text = errorMessage;
      //        //lblMessage.Visible = true;
      //        //return;
      //        Existingphoto = "";
              
      //    }
      //    else
      //    {

      //        filename = fupl_photo.FileName;
      //        Session["photo"] = filename;
      //        Existingphoto = "value";

      //    }
      //    validateForm.AddValidation(Existingphoto, Validation.ValidationCommand.required, "A photo with this name already exists.Please change the name of photo.", "");
      //}

        errorlist.Items.Clear();
        int id = DentistId;
        string sql = "";
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        string medsch = "";
      //  string res = "";
        string spId = "";
        string spec = "";
        //string pSpId = "";
        //string pSpec = "";
        string sSpId = "";
        string sSpec = "";
      //  string resId = "";
        string medId = "";
      //  string felId = "";
        string sCost = "";

        SqlDataReader rdr = null;        

        if (id != 0)
        {
            sb.Append("select D.Cost");
            sb.Append(",D.GraduationYear");
            sb.Append(",S.Id AS SID, S.[specialty] AS Speciality");
            //sb.Append(",P.Id AS PID,P.[specialty] AS PSpeciality");
            sb.Append(",SS.Id AS SSID,SS.[specialty] AS SSpeciality");
            sb.Append(",D.Medicalschool AS mId, M.MedicalSchool");                        
            //sb.Append(",D.Upin");
            sb.Append(" from tbl_dentists as D");
            sb.Append(" left outer join tbl_DentistSpecialty AS S ON D.SpecialityID = S.Id");
            //sb.Append(" left outer join tbl_DentistPrimarySpecialty AS P ON D.PrimarySpecialityID = P.Id");
            sb.Append(" left outer join tbl_DentistSubSpecialty AS SS ON D.SecondarySpecialityID = SS.Id");
            sb.Append(" left outer join tbl_MedicalSchool AS M ON M.Id = D.MedicalSchool");
            sb.Append(" WHERE D.Id =" + id);

            sql = sb.ToString();
            lblMedSch.Visible = true;
            rdr = mgr.ExecuteQuery(sql);
            if (rdr.Read())
            {
                medsch = rdr["MedicalSchool"].ToString();
                medId = rdr["mId"].ToString();
                spId = rdr["SID"].ToString();
                spec = rdr["Speciality"].ToString();
                //pSpId = rdr["PID"].ToString();
                //pSpec = rdr["PSpeciality"].ToString();
                sSpId = rdr["SSID"].ToString();
                sSpec = rdr["SSpeciality"].ToString();
                sCost = Convert.ToString(rdr["Cost"]);
                sCost = (sCost.Trim().Length == 0) ? "0" : sCost;
                //Response.Write("Val:" + sCost);
                //Response.End();
            }
            rdr.Close();
            sql = "SELECT H.HName FROM tbl_Hospitals AS H, tbl_doctor_hospital AS D WHERE D.dr_id = "
                + id + "AND D.IsDelete=0 AND H.IsDelete=0 AND D.hospital_id = H.Id";            

            if (!medsch.Trim().Equals(""))
            {
                lblMedSch.Text = medsch;
                hdnMedSch.Value = medId;
            }

            if (!spec.Trim().Equals(""))
                lblSpeciality.Text = spec;
            //if (!pSpec.Trim().Equals(""))
            //    lblPSpeciality.Text = pSpec;
            if (!sSpec.Trim().Equals(""))
                lblSSpeciality.Text = sSpec;            
            hdnSpecialty.Value = spId;            
            //hdnPSpecialty.Value = pSpId;
            hdnSSpecialty.Value = sSpId;
            //txtUpin.Text = upin;

            ddlCost.SelectedValue = sCost;
        }
        
        //to hold password in viewstate
        ViewState["Pwd"] = txtPwd1.Text.Replace("'", "''");

        // checking for duplicate email when inserting a new record                  
        if (id == 0)
        {
            sql = "select 1, isBulk from tbl_dentists where email='" + txtEmail.Text + "' and  isdelete=0 ";
            DataSet dsEmail = mgr.ExecuteQuery(sql, "tbl");
            if (dsEmail.Tables[0].Rows.Count > 0)
            {
                if (!Convert.ToBoolean(dsEmail.Tables[0].Rows[0]["isBulk"]))
                {
                    trError.Visible = true;
                    errorlist.Items.Add("Email already exists!! Please try with a different email id.");
                    e.Cancel = true;
                    if (ViewState["email"] != null)
                    { txtEmail.Text = ViewState["email"].ToString(); }
                    return;
                }
            }
            else
            {
                trError.Visible = false;
            }
        }
        //else
        //{ sql = "select 1, isBulk from tbl_dentists where email='" + txtEmail.Text + "' and id<>" + id + " and  isdelete=0 "; }

        // end checking for duplicate email  
        //Add server side validation 
       // Validation validateForm = new Validation();
       
        validateForm.AddValidation(txtFname.Text.Trim(), Validation.ValidationCommand.required, "Please Enter First Name.", "");

        validateForm.AddValidation(txtLName.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Last Name.", "");

        //check for bulk upload, because incase of a bulk upload editing validation is not mandatory for username and password : K
        //5th November 2006
        bool isBulk = Convert.ToBoolean(mgr.ExecuteScalarQuery("select isbulk from tbl_dentists where id=" + DentistId.ToString()));

        if (!isBulk)
        {
            validateForm.AddValidation(txtEmail.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Email.", "");

            validateForm.AddValidation(txtPwd1.Text, Validation.ValidationCommand.required, "Please Enter Password.", "");
            validateForm.AddValidation(txtPwd1.Text, Validation.ValidationCommand.minlen, "Please Enter  atleast 6 characters in Password.", "6");
            validateForm.AddValidation(txtpwd2.Text, Validation.ValidationCommand.required, "Please Enter Confirm Password", "");

            validateForm.AddValidation(txtEmail.Text.Trim(), Validation.ValidationCommand.email, "Please Enter Correct Email", "");
        }
        //k-code ends
        validateForm.AddValidation(txtTitle.Text.Trim(), Validation.ValidationCommand.required, "Please Enter title.", "");
        validateForm.AddValidation(txtAddress1.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Address1.", "");
        validateForm.AddValidation(txtCity.Text.Trim(), Validation.ValidationCommand.required, "Please Enter city.", "");

        validateForm.AddValidation(txtZipCode.Text.Trim(), Validation.ValidationCommand.required, "Please Enter zip code.", "");
        validateForm.AddValidation(txtAddress1.Text.Trim(), Validation.ValidationCommand.maxlen, "Address 1 Maximum Length is Only 100 Characters", "99");
        validateForm.AddValidation(txtAddress2.Text.Trim(), Validation.ValidationCommand.maxlen, "Address 2 Maximum Length is Only 100 Characters", "99");

        validateForm.AddValidation(ddlState.Text.Trim(), Validation.ValidationCommand.notequal, "Please Select State", "0");
        validateForm.AddValidation(txtCity.Text.Trim(), Validation.ValidationCommand.alphabetic, "Please enter Correct City Name.", "");

        validateForm.AddValidation(txtPhone.Text.Trim(), Validation.ValidationCommand.phone, "Please Enter Correct Telephone Number", "");
        
        ArrayList arr = validateForm.ErrList;
        if ((!validateForm.CheckError()) || (!captcha.IsValid))
        {
            if (!captcha.IsValid)
            {
                arr.Insert(arr.Count, captcha.ErrorMessage);
            }

            e.Cancel = true;
            trError.Visible = true;
            errorlist.DataSource = arr;
            errorlist.DataBind();
            validateForm.ErrList.Clear();
            arr.Clear();
        }
        else { trError.Visible = false; }
        //e.NextStepIndex = 2;
    }
    
    protected void wiz_DentistReg_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {         

        #region -- Value Filling --          
        string tCost = ddlCost.SelectedValue;
        string tFName = txtFname.Text.Replace("'", "''").Trim();
        string tMName = txtMName.Text.Replace("'", "''").Trim();
        string tLName = txtLName.Text.Replace("'", "''").Trim();
        string tEmail = txtEmail.Text.Replace("'", "''").Trim();
        string tPassword = ViewState["Pwd"].ToString(); 
        string tTitle = txtTitle.Text.Replace("'", "''").Trim();
        string tGender = rbGender.Checked ? "M" : "F";
        string tLanguages = txtLanguages.Text.Replace("'", "''").Trim();
        string tPhone = txtPhone.Text.Replace("'", "''").Trim();
        string tFax = txtFax.Text.Replace("'", "''").Trim();
        string tAddress1 = txtAddress1.Text.Replace("'", "''").Trim();
        string tAddress2 = txtAddress2.Text.Replace("'", "''").Trim();
        string tCity = txtCity.Text.Replace("'", "''").Trim();
       // string tCountry = ddlCountry.SelectedItem.Value;
        string tCountryId = ddlCountry.SelectedItem.Value;
        string tState = ddlState.SelectedItem.Value;
        string tCounty = txtCounty.Text.Replace("'", "''").Trim();
        string tZipCode = txtZipCode.Text.Replace("'", "''");
        string tGraduationYear = ddlGradYear.SelectedItem.Text;      
  
        string tHospitalName = hdnHospital.Value.Replace("<BR>", ";");
            tHospitalName = hdnHospital.Value.Replace("<br>", ";");
        
        string tMedicalSchool = hdnMedSch.Value; //Request.Form[GetHTMLNameById(hdnMedSch.ClientID, hdnMedSch.ID)];// Request.Form[GetHTMLNameById(lst_medsch.ClientID, lst_medsch.ID)];
        string tResidencyTraining = Request.Form[GetHTMLNameById(hdnRes.ClientID, hdnRes.ID)]; //txtResidency.Text.Replace("'", "''").Trim();        
        string tInsurance = "";

        // if other Insurance companies added using the Add Button then get those also
        if (Session["InsId"] != null)
        {
            if (Session["InsId"].ToString().Trim().Length > 0)
            {
                if (tInsurance.Trim().Length <= 0)
                    tInsurance = Session["InsId"].ToString().Trim();
                else
                    tInsurance += "," + Session["InsId"].ToString().Trim();
            }
        }
        
        string tAbms_Certified = rbtAbms1.Checked ? "1" : "0";
        //string tPrimarySpecialityID = hdnPSpecialty.Value; //Request.Form[GetHTMLNameById(hdnPSpecialty.ClientID, hdnPSpecialty.ID)].ToString(); //Request.Form[ddlPSpeciality.ClientID.Replace('_', '$')];
        string tSecondarySpecialityID = hdnSSpecialty.Value;// Request.Form[GetHTMLNameById(hdnSSpecialty.ClientID, hdnSSpecialty.ID)].ToString(); // Request.Form[ddlSSpeciality.ClientID.Replace('_', '$')];
        
        string tMajorActivityID = ddlMajorActivity.SelectedItem.Value;
        //string tFellowShip = Request.Form[GetHTMLNameById(hdnFellow.ClientID, hdnFellow.ID)];
        string tAdvTraining = ddlAdvTraining.SelectedValue; //.Equals("1") ? "Y" : "N";
        string tAwards = txtAwards.Text.Replace("'", "''").Trim();
        # endregion

        Validation validateForm = new Validation();
        clsDentist Dentist = new clsDentist();

        //Server Side Validation 
        validateForm.AddValidation(txtGroupPractise.Text, Validation.ValidationCommand.maxlen, "GroupPractice Maximum Length is Only 1000 Characters", "999");
        validateForm.AddValidation(hdnSpecialty.Value, Validation.ValidationCommand.required, "Please select a Specialty", "");

        if (!validateForm.CheckError())
        {
            e.Cancel = true;
            //lblSpeciality.Text = "NONE";
            trError1.Visible = true;
            ErrorList1.DataSource = validateForm.ErrList;
            ErrorList1.DataBind();

            FillControls(DentistId);
            return;
        }
        else
        { trError1.Visible = false; }

        string tSpecialityID = hdnSpecialty.Value;
        string tGroupPractice = txtGroupPractise.Text.Replace("'", "''").Trim();

     //   string sqlQuery = "";
        int id = DentistId;
        int mark = 0;
        
        if (id == 0)
        {
            tbl_Dentist dent = new tbl_Dentist();
            dent.Id = CustomRepository.getMaxDentistId();
            int tId = dent.Id;
            tId++;
            mark = 1;
            #region -- Insert Dentist Data to Database --
            if (Session["photo"] != null)
            {
                filename = Session["photo"].ToString();
            }


            dent.Id = tId;
            dent.photo = filename;
            dent.Abms_CertificationID = ((tAbms_Certified == "1") ? true : false);
            dent.AcceptNew = (ddlnewPat.SelectedValue == "1") ? true : false;
            dent.Address1 = txtAddress1.Text;
            dent.Address2 = txtAddress2.Text;
            dent.AdvancedTraining = ddlAdvTraining.SelectedValue.Substring(0, 1);
            dent.AEGD = ((rbAEGDYes.Checked) ? true : false);
            dent.Awards = txtAwards.Text;
            dent.City = txtCity.Text;
            dent.Cost = Convert.ToByte(ddlCost.SelectedValue);
            dent.CountryId = tCountryId;
            dent.County = txtCounty.Text;
            dent.Email = txtEmail.Text;
            dent.Fax = txtFax.Text;
            dent.FName = txtFname.Text;
            dent.Gender = ((rbGender.Checked) ? "M" : "F");
            dent.GraduationYear = Convert.ToInt32(ddlGradYear.SelectedValue);
            dent.GroupPractice = txtGroupPractise.Text;
            dent.HospitalName = tHospitalName;
            dent.InsuranceIds = tInsurance;
            dent.IsBulk = false;
            dent.IsDelete = false;
            dent.IsSubscribe = false;
            dent.Languages = txtLanguages.Text;
            dent.LName = txtLName.Text;
            if (tMedicalSchool.Trim().Length > 0)
            { dent.MedicalSchool = Convert.ToInt32(tMedicalSchool); }
            else
            { dent.MedicalSchool = 0; }

            dent.MajorActivityID = Convert.ToInt32(ddlMajorActivity.SelectedValue);
            dent.MName = txtMName.Text;
            dent.Password = ViewState["Pwd"].ToString();
            dent.Phone = txtPhone.Text;
            dent.SpecialityID = Convert.ToInt32(tSpecialityID);
            if (tSecondarySpecialityID.Length > 0)
            { dent.SecondarySpecialityID = Convert.ToInt32(tSecondarySpecialityID); }
            else { dent.SecondarySpecialityID = 0; }
            dent.MarksOfDistiction = (rbMarksYes.Checked) ? true : false;
            dent.MedicalSchool = ((tMedicalSchool.Length > 0) ? Convert.ToInt32(tMedicalSchool) : 0);
            dent.SpecialityBoard = ((rbSpYes.Checked) ? true : false);
            dent.State = ddlState.SelectedValue;
            // dent.CountryId = ddlCountry.SelectedValue;
            dent.Title = txtTitle.Text;
            dent.Website = string.Empty;
            dent.ZipCode = txtZipCode.Text;
            dent.RegDate = DateTime.Now;

            // dent.Add();
            CustomRepository.AddDentist(dent);
          
            lblErrorMessage.Text = Dentist.ErrorDescription;
            #endregion
        }
        else
        {           
            mark = 2;
            #region -- Update the dentist data --
           
            Dentist.ID = DentistId;
            if (Session["photo"] != null)
            {
                Dentist.PHOTO = Session["photo"].ToString();
            }
            Dentist.ABMS_CERTIFICATIONID = ((tAbms_Certified == "1") ? true : false);
            Dentist.ACCEPTNEW = (ddlnewPat.SelectedValue == "1") ? true : false;
            Dentist.ADDRESS1 = txtAddress1.Text;
            Dentist.ADDRESS2 = txtAddress2.Text;
            Dentist.ADVANCEDTRAINING = ddlAdvTraining.SelectedValue.Substring(0, 1);
            Dentist.AEGD = ((rbAEGDYes.Checked) ? true : false);
            Dentist.AWARDS = txtAwards.Text;
            Dentist.CITY = txtCity.Text;
            Dentist.COST = Convert.ToInt32(ddlCost.SelectedValue);
            Dentist.COUNTRYID =ddlCountry.SelectedValue;
            Dentist.COUNTY = txtCounty.Text;
            Dentist.EMAIL = txtEmail.Text;
            Dentist.FAX = txtFax.Text;
            Dentist.FNAME = txtFname.Text;
            Dentist.GENDER = ((rbGender.Checked) ? "M" : "F");
            Dentist.GRADUATIONYEAR = Convert.ToInt32(ddlGradYear.SelectedValue);
            Dentist.GROUPPRACTICE = txtGroupPractise.Text;
            Dentist.HOSPITALNAME = tHospitalName;            
            Dentist.INSURANCEIDS = tInsurance;
            Dentist.ISBULK = false;
            Dentist.ISDELETE = false;
            Dentist.ISSUBSCRIBE = false;
            Dentist.LANGUAGES = txtLanguages.Text;
            Dentist.LNAME = txtLName.Text;            
            Dentist.MAJORACTIVITYID = Convert.ToInt32(ddlMajorActivity.SelectedValue);
            if (tMedicalSchool.Trim().Length > 0)
            { Dentist.MEDICALSCHOOL = Convert.ToInt32(tMedicalSchool); }
            else
            { Dentist.MEDICALSCHOOL = 0; }
            Dentist.MNAME = txtMName.Text;
            Dentist.PASSWORD = ViewState["Pwd"].ToString();
            Dentist.PHONE = txtPhone.Text;
            Dentist.SPECIALITYID = Convert.ToInt32(tSpecialityID);
            //if (tPrimarySpecialityID.Length > 0)
            //{ Dentist.PRIMARYSPECIALITYID = Convert.ToInt32(tPrimarySpecialityID); }
            //else { Dentist.PRIMARYSPECIALITYID = 0; }
            if (tSecondarySpecialityID.Length > 0)
            { Dentist.SECONDARYSPECIALITYID = Convert.ToInt32(tSecondarySpecialityID); }
            else { Dentist.SECONDARYSPECIALITYID = 0; }
            Dentist.MARKSOFDISTICTION = (rbMarksYes.Checked) ? true : false;
            Dentist.MEDICALSCHOOL = Convert.ToInt32(tMedicalSchool);
            Dentist.SPECIALITYBOARD = ((rbSpYes.Checked) ? true : false);
            Dentist.STATE = ddlState.SelectedValue;
            Dentist.TITLE = txtTitle.Text;
            Dentist.WEBSITE = string.Empty;
            Dentist.ZIPCODE = txtZipCode.Text;
            //Response.Write(tHospitalName);
            //Response.End();
            Dentist.Update();
          
            lblErrorMessage.Text = Dentist.ErrorDescription;
            //Response.Write("Check <bR>" + Dentist.ErrorDescription);
            //Response.End();
            #endregion            
        }
//        try
//        {
            string[] aHospitalName;
            char[] splitter = { ';' };
            tHospitalName = Server.HtmlDecode(tHospitalName).Replace("<BR>", ";");
            //Response.Write("<textarea cols=80 rows=20>" + tHospitalName + "</textarea>");
            
            aHospitalName = tHospitalName.Split(';');

            //DataSet ds_id = new DataSet();
            StringBuilder sbSQL = new StringBuilder();

            //PROCESS TO LOG ADMIN ACTIVITY - k: 30 April 2007
            SqlParameter[] sqlParam = new SqlParameter[3];
            sqlParam[0] = new SqlParameter("@Dr_ID", SqlDbType.Int);
            sqlParam[1] = new SqlParameter("@AdminID", SqlDbType.Int);
            sqlParam[2] = new SqlParameter("@ActionPerformed", SqlDbType.VarChar, 100);

            //ds_id = mgr.ExecuteQuery(sqlQuery, "tbl");
            if (mark == 1)
            {
                //id = Convert.ToInt32(ds_id.Tables[0].Rows[0]["Dr_ID"]);
                id = Dentist.ID;
                sqlParam[2].Value = "NEW DENTIST ADDED";
            }
            // add hospitals & Insurance
            if (mark == 2)
            {
                string delSql = "delete tbl_Dentist_Hospital where Dnt_ID='" + id + "'; DELETE tbl_Dentist_Insurance WHERE DentistID='" + id + "'";
             //   mgr.ExecuteQuery(delSql);
                mgr.ExecuteScalarQuery(delSql);
                sqlParam[2].Value = "DENTIST UPDATED";
            }            

            if (Session["ADMIN_ID"] != null)
            {
                if (Session["ADMIN_ID"].ToString().Length > 0)
                {
                    sqlParam[0].Value = id;
                    sqlParam[1].Value = Convert.ToInt32(Session["ADMIN_ID"]);
                    mgr.ExecuteUpdate("LOG_ADMIN_ACTIVITY", sqlParam);
                }
            }

            //Response.Write("AD:" + Session["ADMIN_ID"].ToString());

            foreach (ListItem li in lstInsurance.Items)
            {
                if (li.Selected == true && li.Value != "-1")
                    sbSQL.Append("INSERT INTO tbl_Dentist_Insurance(DentistID, InsuranceID) VALUES('" + id + "','" + li.Value + "');");
            }

            if (sbSQL.Length > 0) mgr.ExecuteUpdate(sbSQL.ToString());

            for (int i = 0; i < aHospitalName.Length; i++)
            {
                SqlParameter[] Param = new SqlParameter[2];
                Param[0] = new SqlParameter("@Dr_ID", SqlDbType.VarChar, 15);
                Param[1] = new SqlParameter("@hospital", SqlDbType.VarChar, 500);

                Param[1].Value = aHospitalName[i];
                Param[0].Value = id;
                //Response.Write(" |:" + aHospitalName[i]);
                mgr.ExecuteUpdate("INSERT_DENTISTHOSPITAL", Param);
            }
            Response.Redirect(Session["strHttp"] + "success.aspx?ref=dentist");
            //Response.Redirect(strRedirect);
//        }
//        catch (Exception es)
//        {
//            lblErrorMessage.Text = es.ToString();

            //Response.Write(es.ToString());
            //Response.End();
//        }
    }
    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        string countryID = ddlCountry.SelectedValue;
        // mgr.BindList("select countrycode,countryname from tbl_country", "countryname", "countrycode", ddlCountry, "select");
        mgr.BindList("select stateid,name from tbl_states where CountryID='" + countryID + "'  order by name", "Name", "StateId", ddlState, "-- Any --");
        // mgr.BindList("select stateid,name from tbl_states order by name", "Name", "StateId", ddlState, "-- Any --");
        if (ddlCountry.SelectedValue == "US")
        {
            ddlState.Items.Insert(0, new ListItem("Select a State", "0"));
        }
        else
        {
            ddlState.Items.Insert(0, new ListItem("Select a Province", "0"));
        }
    }
    
}
